package com.example.note.cardlistview;

import android.content.Context;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.axdac.mixbind.TimeLine;
import com.example.note.R;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/10/4 0004.
 */

public class RecycleViewBuilder {
    private View root;
    private RecyclerView recyclerView;
    private TimeLine.Builder timeBuilder;
    private CommonAdapter<JSONObject> commonAdapter;
    private List<JSONObject> jsonObjects;
    private List<CommonAdapter.DataHandler<JSONObject>> handlers;

    public RecycleViewBuilder(Context context){
        root = View.inflate(context, R.layout.view_recycle,null);
        recyclerView = (RecyclerView) root.findViewById(R.id.recycle_list);
        timeBuilder = new TimeLine.Builder();
        jsonObjects = new ArrayList<>();
        handlers = new ArrayList<>();
        commonAdapter = new CommonAdapter<>(jsonObjects,handlers,this);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        //设置adapter
        recyclerView.setAdapter(commonAdapter);
        //设置Item增加、移除动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    public RecycleViewBuilder addDataMaker(Object DataMaker){
        timeBuilder.addlib(DataMaker);
        return this;
    }

    public RecycleViewBuilder addHandler(CommonAdapter.DataHandler<JSONObject> handler){

        handlers.add(handler);
        return this;
    }

    public void reflesh(){
        timeBuilder.run();
    }

    public void reflesh(Object DataMaker){

        timeBuilder = new TimeLine.Builder();
        timeBuilder.addlib(DataMaker);
        timeBuilder.addlib(new TimeLine.timeLinePackage(){
            @TimeLine.TimeLineTick(level = Integer.MAX_VALUE,thread = TimeLine.TimeLineTick.FORGROUND)
            public void handlerData(TimeLine.RunningMsg msg){
                List<JSONObject> jsonObjects = (List<JSONObject>) msg.map.get("data");
                commonAdapter.clear();
                commonAdapter.reflesh(jsonObjects);
            }
        }).run();
    }

    public View getRoot(){
        timeBuilder.addlib(new TimeLine.timeLinePackage(){
            @TimeLine.TimeLineTick(level = Integer.MAX_VALUE,thread = TimeLine.TimeLineTick.FORGROUND)
            public void handlerData(TimeLine.RunningMsg msg){
                List<JSONObject> jsonObjects = (List<JSONObject>) msg.map.get("data");
                commonAdapter.clear();
                commonAdapter.reflesh(jsonObjects);
            }
        }).run();
        return root;
    }

}
